﻿using System;
using HslCommunication;
using HslCommunication.Profinet.Siemens;


namespace NewUI.Service.Hsl;

public class PlcJuanCaiServiceHsl
{
    public readonly SiemensS7Net _plc;
    public bool IsConnected;
    private const string DbBlock = "DB129";
    private const ushort StructSize = 636; // 结构体大小

    public PlcJuanCaiServiceHsl(string ipAddress)
    {
        _plc = new SiemensS7Net(SiemensPLCS.S1500, ipAddress);
        _plc.Rack = 0;
        _plc.Slot = 1;
        _plc.ConnectTimeOut = 3000; // 3秒超时
    }

    public bool Connect()
    {
        if (IsConnected)
        {
            return IsConnected;
        }
        OperateResult result = _plc.ConnectServer();
        if (result.IsSuccess)
        {
            IsConnected = true;
        }
        else
        {
            IsConnected = false;
        }
        return IsConnected;
    }

    public void Disconnect()
    {
        _plc.ConnectClose();
        IsConnected = false;
    }

    public PlcJuanCai ReadJuanCaiData(ushort dbOffset = 0)
    {
        // 读取整个结构体 (636字节)
        PlcJuanCai data = null;
        try
        {
            // OperateResult<byte[]> result1 = _plc.Read($"{DbBlock}.{dbOffset}", StructSize);
            OperateResult<PlcJuanCai> result = _plc.ReadCustomer<PlcJuanCai>($"{DbBlock}.{dbOffset}");
            return result.Content;
        }
        catch (Exception e)
        {
            Console.WriteLine(e);
        }
        return null;
    }

    public bool WriteJuanCaiData(PlcJuanCai data, ushort dbOffset = 0)
    {
        // 写入整个结构体 (636字节)
        try
        {
            // PLC.adr_JC_SSD_RRP_In = AppSett.GetValue("PLC", "adr_JC_SSD_RRP_In", "DB129.1274");
            OperateResult result = _plc.WriteCustomer($"{DbBlock}.{dbOffset}", data);
            if (result.IsSuccess)
            {
                return true;
            }
        }
        catch (Exception e)
        {
            Console.WriteLine(e);
        }
        return false;
    }
}